/*
 * Copyright (c) csii.com.cn 2016 zhaojin
 */

package com.csii.ssm.util;

import com.alibaba.fastjson.JSON;
import com.csii.ssm.core.CommonDict;
import com.csii.ssm.dto.AjaxData;
import com.csii.ssm.exception.CoreRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.csii.ssm.dto.AjaxData.AjaxDataField.errcode;
import static com.csii.ssm.dto.AjaxData.AjaxDataField.errmsg;
import static com.csii.ssm.dto.AjaxData.AjaxDataField.status;

/**
 * 控制器工具类
 *
 * @author zhaojin 15398699939@163.com
 * @create 2016-04-22-下午5:37
 */
@Component
@Scope("singleton")
public class ControllerUtil{

    private static final Logger logger = LoggerFactory.getLogger(ControllerUtil.class);
    private static final String ACCEPT = "Accept";
    /**
     * 一般pc或者mac上 的浏览器都会进行accept的伪装,如mac chrom:
     * text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8
     */
    private static final String ACCEPT_HTML = "html";
    private static final String UFT8 = "UTF-8";
    private static final String GBK = "GBK";
    private static final List<String> JSON_ACCEPTS = Arrays.asList(new String[]{"application/json"});

    /**
     * @param commonRuntimeException
     * @param resp
     * @param req
     * @param url500                 重定向的交易码
     */
    public static void innerHandlerException(CoreRuntimeException commonRuntimeException, HttpServletResponse resp, HttpServletRequest req, String url500) {
        String accept = req.getHeader(ACCEPT);
        for (String jaccept : JSON_ACCEPTS) {
            if (Arrays.asList(accept.split(",")).contains(jaccept)) {
                //客户端需要返回json类型的数据
                handlerExReturnJson(commonRuntimeException, resp);
                return;
            }
        }
        handlerExReturnHtml(commonRuntimeException, resp, url500);
    }

    private static void handlerExReturnHtml(CoreRuntimeException commonRuntimeException, HttpServletResponse resp, String url500) {
        try {
            String errorMsg = commonRuntimeException.paserPropertiesMsgForKey(commonRuntimeException);
            url500 = new StringBuffer(url500).append("?")
                    .append(String.valueOf(errmsg)).append("=").append(URLEncoder.encode(errorMsg, UFT8)).append("&")
                    .append(String.valueOf(errcode)).append("=").append(URLEncoder.encode(commonRuntimeException.getMessage(), UFT8)).toString();
            logger.info("报错信息:{},响应500页面:{}", errorMsg, url500);
            resp.sendRedirect(url500);
        } catch (IOException e) {
            logger.error("针对请求的contentType,响应500页面失败!", e);
            e.printStackTrace();
        }
    }

    public static void handlerExReturnJson(CoreRuntimeException commonRuntimeException, HttpServletResponse resp) {
        //返回json
        resp.setContentType(CommonDict.HTTP_CONTENT_TYPE_JSON_UTF);
        try {
            String msg = commonRuntimeException.paserPropertiesMsgForKey(commonRuntimeException);
            Map<String, Object> ajaxData = new HashMap();
            Map<String, String> map = new HashMap();
            map.put(String.valueOf(status),CommonDict.AJAXDATA_STATUS_ERROR);
            map.put(String.valueOf(errcode), commonRuntimeException.getMessage());
            map.put(String.valueOf(errmsg), msg);
            ajaxData.put(CommonDict.RES, map);
            String resData = JSON.toJSONString(ajaxData);
            logger.info("针对请求的contentType非HTML的情况,响应JSON:{}:", resData);
            resp.getWriter().write(resData);
        } catch (Exception e) {
            logger.error("针对请求的contentType非HTML的情况,,响应JSON失败!", e);
            e.printStackTrace();
        }
    }

}
